﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace Common.Threading
{
    public static class ReaderWriterLockSlimEx
    {
    }

    public sealed class ReaderLock : IDisposable
    {
        private ReaderWriterLockSlim m_Sync;
        private Boolean m_Upgreadeable;

        public ReaderLock(ReaderWriterLockSlim sync)
            : this(sync, false)
        {
        }

        public ReaderLock(ReaderWriterLockSlim sync, Boolean upgradeable)
        {
            this.m_Sync = sync;
            this.m_Upgreadeable = upgradeable;

            if (this.m_Upgreadeable)
            {
                this.m_Sync.EnterUpgradeableReadLock();
            }
            else
            {
                this.m_Sync.EnterReadLock();
            }
        }

        ~ReaderLock()
        {
            this.Dispose();
        }

        public void Dispose()
        {
            if (this.m_Sync != null)
            {
                if (this.m_Upgreadeable)
                {
                    this.m_Sync.ExitUpgradeableReadLock();
                }
                else
                {
                    this.m_Sync.ExitReadLock();
                }

                this.m_Sync = null;
            }
        }
    }

    public sealed class WriterLock : IDisposable
    {
        private ReaderWriterLockSlim m_Sync;

        public WriterLock(ReaderWriterLockSlim sync)
        {
            this.m_Sync = sync;
            this.m_Sync.EnterWriteLock();
        }

        ~WriterLock()
        {
            this.Dispose();
        }

        public void Dispose()
        {
            if (this.m_Sync != null)
            {
                this.m_Sync.ExitWriteLock();
                this.m_Sync = null;
            }
        }
    }
}
